<template>
  <div class="layout-padding">      
      <div class="table-box"> 
        <ProTable
			ref="proTableRef"
			title="代码生成列表"
			:columns="columns"
			:requestApi="codeGenApi.getBaseInfoPage"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
    <template #tableHeader>
				<el-button type="primary" icon="ele-Plus" @click="openAddNewBox()" >新建模板</el-button>
			</template>
    <template #operation="scope">     
      <el-button icon="ele-Edit" size="small" text type="primary" @click="handleEdit(scope.row)"> 
          {{$t('message.commonBtn.edit')}}</el-button>
      <el-button icon="ele-Delete" size="small" text type="danger" @click="handleDel(scope.row.id)"> {{$t('message.commonBtn.delete')}} </el-button>   
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-button text size="small">更多<i class="el-icon-arrow-down el-icon--right"></i>                
            </el-button>
          </span>
          <template v-slot:dropdown>
            <el-dropdown-menu>
            <el-dropdown-item @click.native="toggleWebType(scope.row)">更改模式
            </el-dropdown-item>
            <el-dropdown-item @click.native="copy(scope.row.id)">复制模板</el-dropdown-item>
            <el-dropdown-item @click.native="download(scope.row)">下载代码</el-dropdown-item>
            <el-dropdown-item @click.native="preview(scope.row)">预览代码</el-dropdown-item>
          </el-dropdown-menu>
          </template>                  
        </el-dropdown>  
    </template>
  </ProTable>          
      </div>
      <Form  ref="FormRef"  :categoryList="state.categoryList"/>
    <AddBox ref="addBoxRef" @add="openForm"/>
  </div>    
</template>

<script setup lang="tsx" name="generator-webForm">
import { defineAsyncComponent, nextTick, reactive,ref, watchEffect } from 'vue'
import { SysDictData } from '/@/api-services/models/system';
import { CodeGenData } from '/@/api-services/models/codeGen';
import { ElMessage, ElMessageBox } from 'element-plus';
import { feature } from '/@/utils/axios-utils';
import { useI18n } from 'vue-i18n';
import { ColumnProps, EnumProps } from "/@/components/ProTable/interface";
import codeGenApi from '/@/api-services/apis/generator/codeGenApi';
import ProTable from "/@/components/ProTable/index.vue";
import dictDataApi from '/@/api-services/apis/system/dictDataApi';
const Form = defineAsyncComponent(() => import('/@/views/generator/webForm/Form.vue'));
const AddBox = defineAsyncComponent(() => import('/@/views/generator/component/AddBox.vue'));
const { t } = useI18n();
const FormRef=ref();
const proTableRef = ref();
const addBoxRef=ref();

const initParam = reactive({ 
  name: '', 
  category:''
});
const state=reactive({
  previewVisible: false,
  downloadFormVisible: false,
  sort: 'webForm',  
  list: [] as Array<CodeGenData>,
  tableParams:{
    pageIndex: 1,
		pageSize: 10,
  },
  listLoading: false,
  currRow: {} as CodeGenData,//当前信息
  categoryList: [] as Array<SysDictData>,
  paras:[] as EnumProps[]
})

const columns: ColumnProps<CodeGenData>[] = [
  {prop:"name", label:"名称",search:{el:"input"}},
  {prop:"code", label:"编码"},
  {prop:"category", label:"分类",
  enum:state.paras,
  search:{el:"select" , props: { filterable: true } },
  render:scope=>{
    var data=state.categoryList.filter(item=>item.value==scope.row.category)[0]
    return (<el-tag size={data.tagSize} type={data.tagType}> {data.name}</el-tag>)    
    }
  },
  {prop:"type", label:"模式",  align:"center",
  render:scope=>{
    return (scope.row.type=='form'?"表单":scope.row.type=='list'?"列表":"流程")    
    }
  },
  {prop:"createrUser", label:"创建人", },
  {prop:"createTime", label:"创建时间", }  ,    
  {prop:"updateTime", label:"最后修改时间"  },
  {prop: "operation", label: "操作", fixed: "right", width: 330 }
]

//查询业务类型
const queryBusinessCategory=async()=>{
  var res = await dictDataApi.getDatalistByType("BusinessCategory")
	state.categoryList=res.data.data??[]
  state.categoryList.forEach(item=>{
    var cur={} as EnumProps
    cur.label=item.name
    cur.value=item.value
    state.paras.push(cur)
  })
}

watchEffect(() => {
	queryBusinessCategory()
});
//数据回显处理
const dataCallback = (queryRes: any) => {
  var data=queryRes.data;
	return {
		items: data.items,
		totalCount: data.totalCount,
		pageIndex: data.pageIndex,
		pageSize: data.pageSize
	};
};

const download=(row:any)=> {
  state.downloadFormVisible = true
  nextTick(() => {
    console.log(row)
    //DownloadFormRef.value.init(row.tables, row.id)
  })
}
const preview=(row:any)=> {
  state.previewVisible = true
  nextTick(() => {
    console.log(row)
    //DownloadFormRef.value.init(row.tables, row.id)
  })
}  
//更改类型
const toggleWebType=(row:CodeGenData) =>{
      const { type } = row
      if (!type) return
      state.currRow=JSON.parse(JSON.stringify(row));
      addBoxRef.value.openDialog(type)
    };
//新建
const openAddNewBox=()=>{
  addBoxRef.value.openDialog('');
}

const handleEdit=(row:CodeGenData)=>{
  FormRef.value.openDialog(row)
}
//模式选择后，打开form设计
const openForm=(webType:string)=>{
  state.currRow.type=webType
  FormRef.value.openDialog(state.currRow)
}


const handleDel=(row:any)=>{
  ElMessageBox.confirm(`${t('message.posAlter.isDeletePos')}:【${row.name}】?`, t('message.posAlter.alter'), {
		confirmButtonText: t('message.posAlter.confirm'),
		cancelButtonText:  t('message.posAlter.cancel'),
		type: 'warning',
	})
  .then(async () => {
    const [err]=await feature(codeGenApi.delete([{id:row.id} ]))
    if(err){
      ElMessage.error(err.message)
    }
    else{
      ElMessage.success(t('message.posAlter.deleteSuccess'));
      proTableRef.value.getTableList()
    }			
  })
}
const copy=(id:number)=> {
  console.log('cope',id)
}
</script>